<script setup lang="ts">

import {Refresh, Search,UploadFilled} from "@element-plus/icons-vue";
import {reactive, ref} from "vue";
import {ElMessage, FormInstance, FormRules,UploadProps} from "element-plus";
import {
    addClassList,
    classList,
    collegeList,
    delClassList,
    editClassList,
    getTeacherList
} from "@/api/interface/reuqest";
import {viewArticle} from "@/api/interface/interfaceRequest";
import {getToken} from "@/utils/auth";

//文件定义请求头
let headers = ref({'Authorization': getToken()})
//首页
const formInline = reactive({
    changeCollege: '',
    className: ''
})
const tableData = ref([])

//主体
const dialogFormVisible = ref(false)
const editPop = ref(false)
const innerVisible = ref(false)
const addMultiple = ref(false)
const delPop = ref(false)
const importFormVisible = ref(false)

interface RuleForm {
    className: string
    collegeName: string
    teacher: string
}

//页面展示
let classObj = ref<viewArticle>({
    pageNum: 1,
    pageSize: 5,
})
let total = ref()

//展示课程
function getList() {
    classList(classObj.value).then((item) => {
        let obj = {}
        // console.log(item)
        total.value = item.total
        tableData.value = item.rows.map((value, index) => {
            obj = {
                serial: index + 1,
                collegeName: value?.college,
                className: value?.name,
                teacher: value?.userName,
                time: value?.createTime,
                id: value?.id,
                deptId: value?.deptId,
                userId: value?.userId
            }
            return obj
        })
        // console.log(total.value)
    })
}

getList()

//获取学院类型
let college = ref([])
collegeList().then((item) => {
    if (item.code === 200) {
        college.value = item.data
    }
    // console.log(item.data)
})

//获取所有老师
let teacher = ref([])
getTeacherList().then((item) => {
    if (item.code === 200) {
        teacher.value = item.rows
        // console.log(item)
    }
})

const ruleFormRef = ref<FormInstance>()
// const formRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    className: '',
    collegeName: '',
    teacher: ''
})


const rules = reactive<FormRules<RuleForm>>({
    className: [
        {required: true, message: '请输入班级名称', trigger: 'blur'},
    ],
    collegeName: [
        {
            required: true,
            message: '请选择学院',
            trigger: 'change',
        },
    ],
    teacher: [
        {
            required: true,
            message: '请选择负责老师',
            trigger: 'change',
        },
    ],
})

//表单确认
//添加
function addClass() {
    dialogFormVisible.value = true
}

let addObj = ref({
    name: '',
    deptId: '',
    userId: ''
})
const submitForm = async (formEl: FormInstance | undefined) => {
    addObj.value = {
        name: ruleForm.className,
        deptId: ruleForm.collegeName,
        userId: ruleForm.teacher
    }
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            addMultiple.value = true
            formEl.resetFields()
        } else {
            console.log('error submit!', fields)
        }
    })
}

function ejectAddMultiple() {
    // console.log(addObj.value)
    addClassList(addObj.value).then((item) => {
        if(item.code===200){
            getList()
            dialogFormVisible.value = false
            addMultiple.value = false
            ElMessage.success('添加班级成功')
        }
        // console.log(item)
    }).catch(()=>{
        dialogFormVisible.value = true
        addMultiple.value = true
        ElMessage.error('已有该班级')
    })

}

//表单取消
const resetForm = (formEl: FormInstance | undefined) => {
    dialogFormVisible.value = false
    if (!formEl) return
    formEl.resetFields()
}

//重置
const formRef = ref<FormInstance>()
const reset = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    classObj.value = {
        pageNum: 1,
        pageSize: 5,
    }
    getList()
}

const options = Array.from({length: 10000}).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

//首页搜索
//输入框
function className() {
    classObj.value = {
        pageNum: 1,
        pageSize: 5,
        deptId: formInline.changeCollege,
        name: formInline.className
    }
    getList()
}

//选择框
function handleChange() {
    classObj.value = {
        pageNum: 1,
        pageSize: 5,
        deptId: formInline.changeCollege,
        name: formInline.className
    }
    getList()
}

//分页器
let currentPage = ref<number>()

function handleCurrentChange(newPage) {
    classObj.value = {
        pageNum: newPage,
        pageSize: 5,
    }
    getList()
}

//搜索按钮
function searchBox() {
    classObj.value = {
        pageNum: 1,
        pageSize: 5,
        deptId: formInline.changeCollege,
        name: formInline.className
    }
    getList()
}

//编辑
let editForm = ref({
    changeCollege: '',
    className: '',
    teacher: ''
})
let edit = ref({
    name:'',
    userId:'',
    deptId:'',
    id:''
})
let editId = ref<string>('')
function editClass(data) {
    editPop.value = true
    // console.log(data)
    editForm.value = {
        changeCollege: data.collegeName,
        className: data.className,
        teacher: data.teacher
    }
    editId.value = data.id
}
function editPopWindow() {
    edit.value = {
        name:editForm.value.className,
        userId:editForm.value.teacher,
        deptId:editForm.value.changeCollege,
        id:editId.value,
    }
    console.log(edit.value)
    editClassList(edit.value).then((item)=>{
        if(item.code===200){
            getList()
            innerVisible.value = false
            editPop.value = false
            ElMessage.success('修改班级成功')
        }
        // console.log(item)
    })
}

//删除
let delId = ref<string[]>([])

function delClass(data) {
    delPop.value = true
    delId.value.push(data.id)
    console.log(delId.value)
}

function delPopWindow() {
    delClassList(delId.value).then((item) => {
        if (item.code === 200) {
            classObj.value = {
                pageNum: 1,
                pageSize: 5,
            }
            getList()
            ElMessage.success('删除班级成功')
            delPop.value = false
            delId.value = []
        }
        console.log(item)
    })
}

//上传文件类型查看
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // console.log(rawFile.type)
    if (rawFile.type !== 'application/vnd.ms-excel' && rawFile.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        ElMessage.error('请上传xls、xlsx格式文档')
        return false
    }
    return true
}

//上传成功
function successUpload(){
    ElMessage.success('文件上传成功')
    importFormVisible.value = false
}

</script>

<template>
    <div class="box">
        <!--        头部-->
        <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="formRef">
            <el-form-item label="学院名称" prop="changeCollege">
                <el-select
                    v-model="formInline.changeCollege"
                    placeholder="请选择学院"
                    clearable
                    @change="handleChange"
                >
                    <el-option v-for="item in college" :key="item.deptId" :label="item.deptName" :value="item.deptId"/>
                </el-select>
            </el-form-item>
            <el-form-item label="班级名称" prop="className">
                <el-input @input="className" v-model="formInline.className" placeholder="请输入班级名称"
                          class="className" clearable/>
            </el-form-item>
            <el-form-item class="button">
                <el-button type="primary" :icon="Search" @click="searchBox">搜索</el-button>
                <el-button :icon="Refresh" @click="reset(formRef)">重置</el-button>
            </el-form-item>
        </el-form>
        <!--        主体-->
        <div style="position: relative">
            <el-form-item>
                <el-button type='primary' @click="addClass">
                    添加
                </el-button>
                <el-button type='primary' @click="importFormVisible = true">
                    导入
                </el-button>
            </el-form-item>
            <el-table :data="tableData" style="width: 100%;">
                <el-table-column prop="serial" label="序号" width="200" align="center"/>
                <el-table-column prop="collegeName" label="学院名称" width="280" align="center"/>
                <el-table-column prop="className" label="班级名称" width="200" align="center"/>
                <el-table-column prop="teacher" label="负责老师" width="200" align="center"/>
                <el-table-column prop="time" label="创建时间" width="280" align="center"/>
                <el-table-column prop="operation" label="操作" width="270" align="center">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="editClass(scope.row)">
                            编辑
                        </el-button>
                        <el-button link type="primary" size="small" @click="delClass(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--            分页器-->
            <el-pagination background layout="prev, pager, next" class="page" :default-page-size=5
                           :total='total' :current-page.sync="classObj.pageNum"
                           @current-change="handleCurrentChange"/>
            <!--        添加弹框-->
            <el-dialog v-model="dialogFormVisible" title="添加" width="380" center="true">
                <el-form
                    ref="ruleFormRef"
                    style="max-width: 600px;margin-left: 20px"
                    :model="ruleForm"
                    :rules="rules"
                    label-width="auto"
                    class="demo-ruleForm"
                    status-icon
                >
                    <el-form-item label="学院名称" prop="collegeName">
                        <el-select v-model="ruleForm.collegeName" placeholder="请选择学院">
                            <el-option v-for="item in college" :key="item.deptId" :label="item.deptName"
                                       :value="item.deptId"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="班级名称" prop="className">
                        <el-input v-model="ruleForm.className" placeholder="请输入班级名称"/>
                    </el-form-item>
                    <el-form-item label="负责老师" prop="teacher">
                        <el-select v-model="ruleForm.teacher" placeholder="请选择负责老师">
                            <el-option v-for="item in teacher" :key="item.userId" :label="item.nickName"
                                       :value="item.userId"/>
                        </el-select>
                    </el-form-item>
                    <el-dialog
                        v-model="addMultiple"
                        width="500"
                        title="提示"
                        append-to-body
                    >
                        <div style="margin-top: -20px;">确认添加班级信息</div>
                        <template #footer>
                            <div class="dialog-footer">
                                <el-button @click="addMultiple = false">取消</el-button>
                                <el-button type="primary" @click="ejectAddMultiple">
                                    保存
                                </el-button>
                            </div>
                        </template>
                    </el-dialog>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            保存
                        </el-button>
                    </div>
                </template>
            </el-dialog>
            <!--        编辑弹框-->
            <el-dialog v-model="editPop" title="编辑" width="380" center>
                <el-form
                    style="max-width: 400px;margin-left: 20px"
                    :model="editForm"
                    :rules="rules"
                    label-width="auto"
                    class="demo-ruleForm"
                    status-icon
                >
                    <el-form-item label="学院名称" prop="region">
                        <el-select v-model="editForm.changeCollege">
                            <el-option v-for="item in college" :key="item.deptId" :label="item.deptName"
                                       :value="item.deptId"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="班级名称">
                        <el-input v-model="editForm.className"/>
                    </el-form-item>
                    <el-form-item label="负责老师">
                        <el-select v-model="editForm.teacher">
                            <el-option v-for="item in teacher" :key="item.userId" :label="item.nickName"
                                       :value="item.userId"/>
                        </el-select>
                    </el-form-item>
                </el-form>
                <el-dialog
                    v-model="innerVisible"
                    width="500"
                    title="提示"
                    append-to-body
                >
                    <div style="margin-top: -20px;">确认修改班级信息？</div>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="innerVisible = false">取消</el-button>
                            <el-button type="primary" @click="editPopWindow">
                                保存
                            </el-button>
                        </div>
                    </template>
                </el-dialog>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="editPop = false">取消</el-button>
                        <el-button type="primary" @click="innerVisible = true">
                            保存
                        </el-button>
                    </div>
                </template>
            </el-dialog>
            <!--        删除弹框-->
            <el-dialog v-model="delPop" title="提示" width="430" center="true">
                <sapn>确认删除班级？</sapn>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="delPop = false">取消</el-button>
                        <el-button type="primary" @click="delPopWindow">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
            <!--        导入弹框-->
            <el-dialog v-model="importFormVisible" title="班级导入" width="430" center="true">
                <el-upload
                    class="upload-demo"
                    drag
                    action="/dev-api/student/class/import"
                    :headers="headers"
                    multiple
                    :before-upload="beforeAvatarUpload"
                    :on-success = 'successUpload'
                    :show-file-list = false
                >
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                        将文件拖到此处，或 <em>点击上传</em>
                    </div>
                    <template #tip>
                        <div class="el-upload__tip" style="text-align: center">
                            仅允许导入xls、xlsx格式文件。
                        </div>
                    </template>
                </el-upload>
            </el-dialog>
        </div>
    </div>
</template>

<style scoped lang="scss">
.box {
    padding: 30px 30px 65px;
}

.page {
    //margin-top: 20px;
    //margin-left: 1000px;
    position: absolute;
    //top: 20px;
    bottom: -50px;
    right: 10px;
}

.className {
    width: 170px;
}

.sectionTop {
    display: flex;
}

//上传图片
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

::v-deep(.el-dialog__header) {
    position: relative;
    background-color: #1892FF;

    .el-dialog__headerbtn {
        height: 54.67px;
        position: absolute;
        top: 0px;
        right: -16px;
        background-color: #1892FF;

        svg {
            color: white;
        }
    }

    span {
        color: #FFFFFF;
    }
}

::v-deep(.el-form-item__content) {
    .el-input {
        width: 220px;

        .el-input__wrapper {
            width: 220px;
        }
    }
}

</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
